home *** CD-ROM | disk | FTP | other *** search
/ The Very Best of Atari Inside / The Very Best of Atari Inside 1.iso / mint / mntlb20 / lib / fseek.c < prev    next >
C/C++ Source or Header  |  1991-02-17  |  2KB  |  97 lines

  1. /* something like the origonal
  2.  * from Dale Schumacher's dLibs
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. extern long lseek(), tell();
  8.  
  9. long ftell(fp)
  10. FILE *fp;
  11. {
  12.     long rv, count = fp->_cnt, adjust = 0;
  13.     unsigned int f = fp->_flag;
  14.  
  15.     if( ((f & _IOREAD) && (!(f & _IOBIN))) ||
  16.        (count == 0)               ||
  17.        (f & _IONBF) )
  18.     {
  19.     fflush(fp);    
  20.     rv = lseek(fp->_file, 0L, SEEK_CUR);
  21.     }
  22.     else
  23.     {
  24.     if(f & _IOREAD)
  25.         adjust = -count;
  26.     else if(f & (_IOWRT | _IORW))
  27.     {
  28.         if(f & _IOWRT)
  29.         adjust = count;
  30.     }
  31.     else return -1L;
  32.  
  33.     rv = lseek(fp->_file, 0L, SEEK_CUR);
  34.     }
  35.     return (rv < 0) ? -1L : rv + adjust;
  36. }
  37.  
  38. void rewind(fp)
  39. register FILE *fp;
  40. {
  41.     register long rv;
  42.     
  43.     fflush(fp);
  44.     rv = lseek(fp->_file, 0L, SEEK_SET);
  45.     fp->_flag &= ~(_IOEOF|_IOERR);
  46. }
  47.  
  48. int fseek(fp, offset, origin)
  49. FILE *fp;
  50. long offset;
  51. int origin;
  52. {
  53.     long pos, count;
  54.     unsigned int f;
  55.     int rv;
  56.     
  57.     /* Clear end of file flag */
  58.     f = (fp->_flag &= ~_IOEOF);
  59.     count = fp->_cnt;
  60.     
  61.     if((!(f & _IOBIN))         ||
  62.        (f & (_IOWRT))        ||
  63.        (count == 0)         ||
  64.        (f & _IONBF)        || 
  65.        (origin == SEEK_END) )
  66.     {
  67.     rv = fflush(fp);
  68.     return ((rv == EOF) || (lseek(fp->_file, offset, origin) < 0)) ?
  69.         -1 : 0;
  70.     }
  71.     
  72.     /* figure out if where we are going is still within the buffer */
  73.     pos = offset;
  74.     if(origin == SEEK_SET)
  75.     {
  76.     register long realpos;
  77.     if((realpos = tell(fp->_file)) < 0)
  78.     {    /* no point carrying on */
  79.         return -1;
  80.     }
  81.     pos += count - realpos;
  82.     }
  83.     else offset -= count;    /* we were already count ahead */
  84.     
  85.     if( (!(f & _IORW)) && (pos <= count) && (pos >= (fp->_base - fp->_ptr)) )
  86.     {
  87.     fp->_ptr += pos;
  88.     fp->_cnt -= pos;
  89.     return 0;
  90.     }
  91.     /* otherwise */
  92.     fp->_ptr = fp->_base;
  93.     fp->_cnt = 0;
  94.     if(f & _IORW) fp->_flag &= ~_IOREAD;
  95.     return (lseek(fp->_file, offset, origin) < 0) ? -1 : 0;
  96. }
  97.